package com.flea.repository.jdbc;

import com.flea.model.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author hc24
 * @date 2021.1.21 13:20
 */
@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product,Integer>, ProductComplexRepository {

    Page<Product> findByNameLikeOrDescLike(String name, String desc, Pageable pageable);

//    List<Product> findByNameLikeOrDescLike(String name, String desc, Pageable pageable);
//
//    long countByNameLikeOrDescLike(String name,String desc);

    /**
     * 分页查询用户自己发布的闲置商品
     *
     * @param userId
     * @param pageable
     * @return
     */
    List<Product> findByUserIdAndDescLike(Integer userId, String desc, Pageable pageable);

    long countByUserId(Integer userId);

    /**
     * “乐观锁” 的思想
     *
     * @param productId
     * @param num
     * @param originalNum
     * @return
     */
    @Modifying
    @Query("update product set inventory=inventory-:num where id=:productId and inventory=:originalNum")
    long decInventory(Integer productId, int num, int originalNum);


    List<Product> findByOrderByCreateTimeDesc(Pageable pageable);

}
